package com.atguigu.interview.algo.search;

/**
 * @author Jungle
 * @create 2023-09-13 12:08
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] ins = {1, 2, 6, 9};
        int i = binarySearch(ins, 6);
        System.out.println(i);
    }

    public static int binarySearch(int[] array, int value) {
        int start = 0;
        int end = array.length - 1;

        while (start <= end) {
            int middle = (start + end) / 2;
            if (array[middle] == value) {
                return middle;
            }
            if (array[middle] < value) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }
        return -1;
    }

    /**
     * 二分查找
     */
    public int search01(int[] array, int value) {
        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int middle = (start + end) / 2;
            if (array[middle] == value) {
                return middle;
            }

            if (array[middle] < value) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }
        return -1;
    }
}
